<script setup>
import { getList, createApi, deleteApi, updateApi, updateStatusApi } from '@/api/coupon'
import { ref, onMounted, computed } from 'vue'
import FromDrawer from '@/components/from-drawer.vue'
import { toast } from '@/utils/elnotification'
import ListHeader from '@/components/list-header.vue'

//绑定表格数据
const tableData = ref([])
//总页数
const total = ref(0)
//当前页
const currentPage = ref(1)
//加载动画
const loading = ref(false)
//公告标题
const title1 = ref('')

//获取表格数据
const getData = async (p = null) => {
  if (typeof p === 'number') {
    currentPage.value = p
  }
  loading.value = true
  try {
    const res = await getList(currentPage.value)
    tableData.value = res.list.map((item) => {
      item.statusText = formatStatus(item)
      return item
    })
    total.value = res.totalCount
  } catch (error) {
  } finally {
    loading.value = false
  }
}

//删除公告
const onDelete = async (row) => {
  fromDrawerRef.value.showLoading()
  try {
    await deleteApi(row.id)
    toast('删除成功')
    getData(1)
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    fromDrawerRef.value.hideLoading()
  }
  console.log(row)
}

//新增公告
const fromDrawerRef = ref(null)
const onAdd = () => {
  title1.value = '新增优惠卷'
  changId.value = 0
  fromDrawerRef.value.open()
  form.value = {
    name: '',
    type: 0,
    value: 0,
    total: 100,
    min_price: 0,
    start_time: null,
    end_time: null,
    order: 50,
    desc: ''
  }
}

//表单部分
const formRef = ref(null)
const form = ref({
  name: '',
  type: 0,
  value: 0,
  total: 100,
  min_price: 0,
  start_time: null,
  end_time: null,
  order: 50,
  desc: ''
})

//表单校验规则
const rules = {
  name: [{ required: true, message: '规格昵称不能为空', trigger: 'blur' }],
  default: [{ required: true, message: '规格值不能为空', trigger: 'blur' }]
}

//确认提交
const onSubmit = async () => {
  const val = await formRef.value.validate((val) => val)
  if (!val) return
  fromDrawerRef.value.showLoading()

  if (changId.value !== 0) {
    try {
      console.log(changId.value)
      await updateApi(changId.value, { ...form.value })
      toast('编辑成功')
      getData(1)
    } catch (error) {
      toast('编辑失败', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  } else {
    try {
      await createApi({ ...form.value })
      toast('新增成功')
      getData(1)
    } catch (error) {
      toast('新增失败', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  }
}

//修改公告
const changId = ref(0)
const onChange = (row) => {
  title1.value = '修改优惠卷'
  const { name, type, value, total, min_price, start_time, end_time, order, id, desc } = row
  console.log(row)
  form.value = {
    name,
    type,
    value,
    total,
    min_price,
    start_time,
    end_time,
    order,
    desc
  }
  changId.value = id
  fromDrawerRef.value.open()
}

const formatStatus = (row) => {
  let s = '领取中'
  const start_time = new Date(row.start_time).getTime()
  const now = new Date().getTime()
  const end_time = new Date(row.end_time).getTime()

  if (start_time > now) {
    s = '未开始'
  } else if (end_time < now) {
    s = '已结束'
  } else if (row.status === 0) {
    s = '已失效'
  }
  return s
}

const timerange = computed({
  get() {
    return form.value.start_time && form.value.end_time
      ? [form.value.start_time, form.value.end_time]
      : []
  },
  set(val) {
    form.value.start_time = val[0]
    form.value.end_time = val[1]
  }
})

//失效
const onDisabled = async (row) => {
  console.log(row)
  try {
    await updateStatusApi(row.id, 0)
    toast('已失效')
  } catch (error) {}
}

onMounted(() => {
  getData()
})
</script>

<template>
  <el-card shadow="never" class="border-0" v-loading="loading">
    <ListHeader @create="onAdd" @refresh="getData"></ListHeader>
  </el-card>
  <el-table :data="tableData" stripe style="width: 100%">
    <el-table-column label="优惠卷名称" width="350">
      <template #default="{ row }">
        <div
          class="border border-dashed py-2 px-4 rounded"
          :class="row.statusText == '领取中' ? 'active' : 'inactive'"
        >
          <h5 class="font-bold text-md">{{ row.name }}</h5>
          <small>{{ row.start_time }}-{{ row.end_time }} </small>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="statusText" label="优惠卷状态" align="center" />
    <el-table-column label="优惠" align="center">
      <template #default="{ row }">
        {{ row.type == 0 ? '满减' : '折扣' }}
        {{ row.type == 0 ? '￥' + row.value : row.value + '折' }}
      </template>
    </el-table-column>
    <el-table-column prop="total" label="发放数量" align="center" />
    <el-table-column prop="used" label="已使用" align="center" />
    <el-table-column label="操作" width="250" align="center">
      <template #default="scoped">
        <el-button
          type="primary"
          v-if="scoped.row.statusText == '未开始'"
          size="small"
          text
          @click="onChange(scoped.row)"
          >修改</el-button
        >
        <el-popconfirm
          v-if="scoped.row.statusText != '领取中'"
          title="是否要删除该优惠卷？"
          confirm-button-text="确认"
          cancel-button-text="取消"
          @confirm="onDelete(scoped.row)"
        >
          <template #reference>
            <el-button type="primary" size="small" text>删除</el-button>
          </template>
        </el-popconfirm>
        <el-popconfirm
          v-if="scoped.row.statusText == '领取中'"
          title="是否要让该优惠卷失效？"
          confirm-button-text="失效"
          cancel-button-text="取消"
          @confirm="onDisabled(scoped.row)"
        >
          <template #reference>
            <el-button type="danger" size="small">失效</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <div class="flex justify-center justify-center mt-5">
    <el-pagination
      @current-change="getData"
      :current-page="currentPage"
      background
      layout="prev,pager,next"
      :total="total"
    />
  </div>
  <FromDrawer destroy-on-close ref="fromDrawerRef" :title="title1" @submit="onSubmit">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
      <el-form-item label="优惠卷名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入优惠卷名称" style="width: 80%"></el-input>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio :label="0" border>满减</el-radio>
          <el-radio :label="1" border>折扣</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="面值" prop="value">
        <el-input v-model="form.value" style="width: 50%">
          <template #append>{{ form.type === 0 ? '元' : '折' }}</template>
        </el-input>
      </el-form-item>
      <el-form-item label="发行量" prop="total">
        <el-input-number v-model="form.total" :min="1" :max="1000" style="width: 50%" />
      </el-form-item>
      <el-form-item label="最低使用价格" prop="min_price">
        <el-input-number v-model="form.min_price" :min="1" :max="1000" style="width: 50%" />
      </el-form-item>
      <el-form-item label="排序" prop="order">
        <el-input-number v-model="form.order" :min="1" :max="1000" style="width: 50%" />
      </el-form-item>
      <el-form-item label="活动时间" prop="name">
        <el-date-picker
          v-model="timerange"
          type="datetimerange"
          range-separator="到"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          :editable="false"
        />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="form.desc"></el-input>
      </el-form-item>
    </el-form>
  </FromDrawer>
</template>

<style scoped>
.active {
  @apply border-rose-200 bg-rose-50 text-red-400;
}
.inactive {
  @apply border-gray-200 bg-gray-50 text-gray-400;
}
</style>
